package com.example.dessertstoressm.controller;

import com.example.dessertstoressm.Service.CatalogService;
import com.example.dessertstoressm.domain.Cart;
import com.example.dessertstoressm.domain.CartItem;
import com.example.dessertstoressm.domain.Item;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;


@Controller
public class cartController {

    //购物车页面的支付按钮
    @RequestMapping("newOrderForm")
    public String toPay(){
        return "order/newOrder";
    }



    @Autowired
    public Cart cart;
    public Item item;
    @Resource
    public CatalogService catalogService;
    @RequestMapping("/addItemToCart")
    public String addItemToCart( HttpServletRequest req){


        String workingItemId = req.getParameter("workingItemId");
        HttpSession session = req.getSession();
        cart = (Cart) session.getAttribute("cart");

        /*
        String flaginRequest = req.getParameter("flag");
        Integer flaginSession = (Integer)session.getAttribute("flag");
        String sessionFlag = flaginSession.toString();

         */

        if (cart == null) {
            cart = new Cart();
        }


        if (cart.containsItemId(workingItemId)) {
            cart.incrementQuantityByItemId(workingItemId);

        } else {

             //数据库操作

            boolean isInStock = catalogService.isItemInStock(workingItemId);
            item = catalogService.getItem(workingItemId);
            System.out.println("找到的是"+item.getItemId());
            cart.addItem(item, isInStock);


            }
        int cartItemsNum = cart.getNumberOfItems();
        session.setAttribute("cartItemsNum",cartItemsNum);
        session.setAttribute("cartItems", cart.getCartItemList());
        session.setAttribute("cart",cart);
        return "cart/cart";

        }


        @RequestMapping("removeCartItem")
        public String removeCartItem(HttpServletRequest req){
            HttpSession session = req.getSession();
            Cart cart = (Cart) session.getAttribute("cart");

            String workingItemId = req.getParameter("workingItemId");

            Item item = cart.removeItemById(workingItemId);

            if(item==null){
                session.setAttribute("errorMsg","进行移除的购物车项目为空");
                return "common/error";
                //req.getRequestDispatcher(ERROR_FORM).forward(req,resp);
            }else{
                return "cart/cart";
            }
        }




        @PostMapping("updateCartByInput")
        @ResponseBody
        public String updateBtInput(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            //从对话中，获取购物车
            HttpSession session = req.getSession();
            Cart cart = (Cart)session.getAttribute("cart");
            Iterator<CartItem> cartItems = cart.getAllCartItems();
            while(cartItems.hasNext()){
                CartItem cartItem =(CartItem) cartItems.next();
                String itemId = cartItem.getItem().getItemId();
                try{
                    String str = req.getParameter("itemId");
                    String []array=str.split(",");
                    String []array_2=array[1].split("=");
                    if(itemId.equals(array[0]))
                        cart.setQuantityByItemId(itemId, Integer.parseInt(array_2[1]));
                    //取到值以后如果无数量就不显示了
                    if(Integer.parseInt(array[1])<1)
                    {
                        cartItems.remove();
                    }
                }catch(Exception e){
                }
            }
            session.setAttribute("cart", cart);

            Cart cart2 = (Cart)session.getAttribute("cart");
            Iterator<CartItem> cartItemIterator2 = cart2.getAllCartItems();
            String quantityAll = "";
            while (cartItemIterator2.hasNext()) {
                //产品数量增加
                CartItem cartItem2 = cartItemIterator2.next();
                int quantity2 = cartItem2.getQuantity();
                quantityAll += quantity2 + "," + cartItem2.getTotal() + "," + cart2.getSubTotal();
            }
            resp.setContentType("text/xml");
            PrintWriter out = resp.getWriter();
            out.write(quantityAll);

            resp.setHeader("Access-Control-Allow_Origin","*");
            return "cart/cart";

        }

        @PostMapping("updateCart")
        public String updateCart(HttpServletRequest req){
            HttpSession session = req.getSession();
            Cart cart = (Cart) session.getAttribute("cart");

            Iterator<CartItem> cartItems = cart.getAllCartItems();

            while(cartItems.hasNext()){
                CartItem cartItem =(CartItem) cartItems.next();
                String itemId = cartItem.getItem().getItemId();


                try{

                    String quantityString = req.getParameter(itemId);

                    //拿到用户输入的text里面的quantity数字
                    int quantity = Integer.parseInt(quantityString);
                    cart.setQuantityByItemId(itemId,quantity);

                    //取到值以后如果无数量就不显示了
                    if(quantity<1)
                    {
                        cartItems.remove();
                    }

                }catch(Exception e){

                }


            }
            return "cart/cart";
        }

}





